/*
 * Copyright (c) 2012 Universidad Antonio de Nebrija.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Apache License v2.0
 * which accompanies this distribution, and is available at
 * http://www.apache.org/licenses/LICENSE-2.0.html
 * 
 * Contributors:
 *    Universidad Antonio de Nebrija - initial API, implementation and documentation
 */
package com.nebrija.riif.parser;

import org.antlr.runtime.tree.Tree;

import com.nebrija.riif.model.ChildComponent;
import com.nebrija.riif.model.ChildComponentList;
import com.nebrija.riif.model.ChildComponentUnit;
import com.nebrija.riif.model.Component;
import com.nebrija.riif.model.RIIFElement;
import com.nebrija.riif.model.RootClass;

/**
 * Class to process a child_component token and convert it to the associated object from the model
 * @author asanchep
 *
 */
public class ChildComponentProcessor implements RIIFParserProcessor {

	@Override
	public RIIFElement apply(RIIFElement container, Tree t) {
		// Only components are supported as containers at this moment
		if(! (container instanceof Component)){
			return null;
		}
		// Get the component id this child_component references
		String baseid = t.getChild(0).getText();
		// Get the child_component id
		String id = t.getChild(1).getText();
		
		// Look for the referenced component
		RIIFElement element = RootClass.getInstance().getElement(baseid);
		
		// If it is not a valid component, return null
		if(element==null || !(element instanceof Component)){
			return null;
		}
		
		ChildComponent cc = null;
		// It could be a single child component or an array
		StringBuilder indexes = new StringBuilder();
		// When it is an array, there are more children
		if(t.getChildCount()>2){
			for (int i=2;i<t.getChildCount();i++){
				indexes.append(t.getChild(i).getText());
			}
			cc = new ChildComponentList(id, (Component)container, (Component)element, indexes.toString());
			((Component)container).addChildComponent(cc);
		} else {
			cc = new ChildComponentUnit(id, (Component)container, (Component)element);
			((Component)container).addChildComponent(cc);
		}
		

		return cc;
	}
	

}
